<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="name" label="名称" width="200" header-align="center" sortable>
      </el-table-column>
      <el-table-column prop="url" label="访问路径" width="250" header-align="center" sortable>
      </el-table-column>
      <el-table-column prop="descs" label="描述" width="150" header-align="center" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="标识" width="350" header-align="center" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="父权限" width="200" align="center" sortable>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面
    :visible.sync="outerVisible" 新版本打开对话框
    v-model="permissionFormVisible" 老版本打开对话框
    -->
    <el-dialog title="新增或修改" :visible.sync="permissionFormVisible" :close-on-click-modal="false">
      <el-form :model="permission" label-width="80px" :rules="permissionFormRules" ref="permissionForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="permission.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门经理" prop="manager">
          <el-select v-model="permission.manager" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
               必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="permission.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="permission.intro"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="permissionFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="permissionLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //分页相关
      query:{
        currentPage:1,
        pageSize:10,
        keyword:''
      },
      pageInfo:{
        total:0,
        rows:[]
      },
      listLoading: false,
      sels: [],//列表选中列

      permissionFormVisible: false,//新增界面是否显示
      permissionLoading: false,
      permissionFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      //新增界面数据
      permission: {
        id:null,
        name: '',
        intro: '',
        parent: {},
        manager: {},
      },
      employees:[],
      deptTree:[]

    }
  },
  methods: {
    //获取用户列表
    getDeptTree() {
      //发起请求获取数据
      this.$http.get("/permission/tree")
          .then(result =>{
            result = result.data; //{success,result:{}}
            if (result.success){
              this.deptTree = result.data;
            }else{
              this.$message({
                message: '获取部门树失败！'+result.message,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },
    //获取用户列表
    getEmployees() {
      //发起请求获取数据
      this.$http.get("/employee")
          .then(result =>{
            result = result.data; //{success,result:{}}
            if (result.success){
              this.employees = result.data;
            }else{
              this.$message({
                message: '获取员工数据失败！'+result.message,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },
    search(){
      //重置当前页为第一页
      this.query.currentPage =1;
      this.getPermissions();
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(val) {
      this.query.currentPage= val;
      this.getPermissions();
    },
    //获取用户列表
    getPermissions() {
      this.listLoading = true; //发起请求之前显示加载条
      //发起请求获取数据
      this.$http.post("/permission",this.query)
          .then(result =>{
            result = result.data; //{success,result:{}}
            if (result.success){
              this.pageInfo = result.data;
              console.log(result.data);
            }else{
              this.$message({
                message: '获取分页数据失败！'+result.message,
                type: 'error'
              });
            }
            this.listLoading = false;
          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = row.id;
        this.$http.delete("/permission/"+para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getPermissions();
        });
      }).catch(() => {
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.permissionFormVisible = true;
      this.permission = Object.assign({}, row); //回显
      //获取所有员工信息来选择部门经理
      this.getEmployees();
      //获取部门树
      this.getDeptTree();
      let path = this.permission.path; //包含自己/ 1/4/20
      if (path){
        let paths = path.split("/"); //["",1,4,20]
        let idsStr = paths.slice(1,paths.length-1);//[1,4]
        let idsInt = [];
        for (let i = 0; i <idsStr.length ; i++) {
          idsInt.push(parseInt(idsStr[i]));
        }
        //做部门的回显
        this.permission.parent = idsInt;
      }

    },
    //显示新增界面
    handleAdd: function () {
      this.permissionFormVisible = true;
      this.addForm =  {
        id:null,
        name: '',
        intro: '',
        parent: {},
        manager: {},
      }

      //获取所有员工信息来选择部门经理
      this.getEmployees();
      //获取部门树
      this.getDeptTree();
    },
    //编辑
    save: function () {
      this.$refs.permissionForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.permissionLoading = true;
            let para = Object.assign({}, this.permission);
            //把数据转换成我们想要格式 parent: [1, 4]---》parent:{id:4}

            /*if(para.parent){// [2,7]
              para.parent = {"id":para.parent[para.parent.length-1]}
            }*/
            if (para.parent){
              let parentIds = para.parent; // [1, 4]
              let parentId = parentIds[parentIds.length-1]; // 4
              para.parent = {"id":parentId} //parent:{id:4}
            }

            this.$http.put("/permission",para).then((res) => {
              res = res.data;

              if (res.success){
                this.$message({
                  message: '保存成功',
                  type: 'success'
                });

                this.permissionFormVisible = false; //关闭对话框

                this.$refs['permissionForm'].resetFields(); //重置表单

                this.getPermissions(); //重新加载数据
              }else{
                this.$message({
                  message: '保存失败,'+res.message,
                  type: 'error'
                });
              }

              this.permissionLoading = false; //关闭加载条
            });
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/permission/batch",ids).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getPermissions();
        });
      }).catch(() => {
      });
    }
  },
  mounted() {
    this.getPermissions();
  }
}

</script>

<style scoped>

</style>
